package com.yix.admin.modules.system.controller;

import cn.hutool.core.lang.Dict;
import com.yix.admin.modules.system.entity.SysRole;
import com.yix.admin.modules.system.entity.dto.SysRoleDto;
import com.yix.admin.modules.system.entity.dto.SysRoleSmallDto;
import com.yix.admin.modules.system.entity.query.SysRoleQuery;
import com.yix.admin.modules.system.service.SysRoleService;
import com.yix.common.exception.BadRequestException;
import com.yix.common.utils.SecurityUtils;
import com.yix.logging.annotation.LogAop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author wdx
 * @version 1.0
 * @Description TODO
 * @date 2021/2/5 16:56
 */
@RestController
@Api(tags = "系统：角色管理")
@RequestMapping("/api/roles")
public class SysRoleController {
    @Autowired
    private SysRoleService sysRoleService;
    private static final String ENTITY_NAME = "role";

    @ApiOperation("获取单个role")
    @GetMapping(value = "/{id}")
    @PreAuthorize("@el.check('roles:list')")
    public ResponseEntity<Object> query(@PathVariable String id){
        return new ResponseEntity<>(sysRoleService.findById(id), HttpStatus.OK);
    }

    @ApiOperation("导出角色数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('role:list')")
    public void download(HttpServletResponse response, SysRoleQuery criteria) throws IOException {
        sysRoleService.download(sysRoleService.queryAll(criteria), response);
    }

    @ApiOperation("返回全部的角色")
    @GetMapping(value = "/all")
    @PreAuthorize("@el.check('roles:list','user:add','user:edit')")
    public ResponseEntity<Object> query(){
        return new ResponseEntity<>(sysRoleService.queryAll(),HttpStatus.OK);
    }

    @ApiOperation("查询角色")
    @GetMapping
    @PreAuthorize("@el.check('roles:list')")
    public ResponseEntity<Object> query(SysRoleQuery criteria, Pageable pageable){
        return new ResponseEntity<>(sysRoleService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @ApiOperation("获取用户级别")
    @GetMapping(value = "/level")
    public ResponseEntity<Object> getLevel(){
        return new ResponseEntity<>(Dict.create().set("level", getLevels(null)),HttpStatus.OK);
    }

    @LogAop("新增角色")
    @ApiOperation("新增角色")
    @PostMapping
    @PreAuthorize("@el.check('roles:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody SysRole resources){
        if (resources.getId() != null) {
            throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
        }
        getLevels(resources.getLevel());
        sysRoleService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @LogAop("修改角色")
    @ApiOperation("修改角色")
    @PutMapping
    @PreAuthorize("@el.check('roles:edit')")
    public ResponseEntity<Object> update(@Validated(SysRole.Update.class) @RequestBody SysRole resources){
        getLevels(resources.getLevel());
        sysRoleService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @LogAop("修改角色菜单")
    @ApiOperation("修改角色菜单")
    @PutMapping(value = "/menu")
    @PreAuthorize("@el.check('roles:edit')")
    public ResponseEntity<Object> updateMenu(@RequestBody SysRole resources){
        SysRoleDto role = sysRoleService.findById(resources.getId());
        getLevels(role.getLevel());
        sysRoleService.updateMenu(resources,role);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @LogAop("删除角色")
    @ApiOperation("删除角色")
    @DeleteMapping
    @PreAuthorize("@el.check('roles:del')")
    public ResponseEntity<Object> delete(@RequestBody Set<String> ids){
        for (String id : ids) {
            SysRoleDto role = sysRoleService.findById(id);
            getLevels(role.getLevel());
        }
        // 验证是否被用户关联
        sysRoleService.verification(ids);
        sysRoleService.delete(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 获取用户的角色级别
     * @return /
     */
    private int getLevels(Integer level){
        List<Integer> levels = sysRoleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(SysRoleSmallDto::getLevel).collect(Collectors.toList());
        int min = Collections.min(levels);
        if(level != null){
            if(level < min){
                throw new BadRequestException("权限不足，你的角色级别：" + min + "，低于操作的角色级别：" + level);
            }
        }
        return min;
    }
}
